package com.jmgd.cjlx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jmgd.cjlx.constants.DzApplicationCommon;
import com.jmgd.cjlx.dao.*;
import com.jmgd.cjlx.entity.*;
import com.jmgd.cjlx.param.dz.*;
import com.jmgd.cjlx.param.mom.ASN;
import com.jmgd.cjlx.param.mom.ASNList;
import com.jmgd.cjlx.service.DzGyService;
import com.jmgd.cjlx.util.HttpPostRequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class DzGyServiceImpl implements DzGyService {
    private static final Logger logger = LoggerFactory.getLogger(DzGyServiceImpl.class);


    @Autowired
    TCjLxWarePriceMapper tCjLxWarePriceMapper;

    @Autowired
    TCjLxWareMapper tCjLxWareMapper;

    @Autowired
    TCjLxWareQtyMapper tCjLxWareQtyMapper;

    @Autowired
    TCjLxLogMapper tCjLxLogMapper;

    @Autowired
    TCjLxOrderHMapper tCjLxOrderHMapper;

    @Autowired
    TCjLxOrderDMapper tCjLxOrderDMapper;

    @Autowired
    TCjLxOrderTakeHMapper tCjLxOrderTakeHMapper;

    @Autowired
    TCjLxOrderTakeDMapper tCjLxOrderTakeDMapper;

    @Autowired
    TCjLxOrderSendHMapper tCjLxOrderSendHMapper;

    @Autowired
    TCjLxOrderSendDMapper tCjLxOrderSendDMapper;

    @Autowired
    TLxCallbackLogMapper tLxCallbackLogMapper;



    @Override
    @Async
    public void callBack(Object object) {
//        String jsonString = "{\"appId\":\"e8ef6b314e6a0ec62a570151eefb15ff\",\"method\":\"m_create_order_callback\",\"timestamp\":\"1719562860400\",\"signType\":\"HMAC_SHA256\",\"content\":\"{\\\"ordercode\\\":\\\"1719562860400\\\",\\\"b2bordercode\\\":\\\"Q04022014\\\",\\\"total\\\":1025.9,\\\"status\\\":1,\\\"errorcode\\\":0,\\\"errormsg\\\":null,\\\"items\\\":[{\\\"itemcode\\\":\\\"0\\\",\\\"goodsid\\\":\\\"H359521N\\\",\\\"goodsqty\\\":5,\\\"price\\\":167.38,\\\"subtotal\\\":836.9,\\\"udf1\\\":null,\\\"udf2\\\":null,\\\"udf3\\\":null,\\\"udf4\\\":null,\\\"udf5\\\":null,\\\"udf6\\\":null,\\\"udf7\\\":null,\\\"udf8\\\":null,\\\"udf9\\\":null,\\\"udf10\\\":null},{\\\"itemcode\\\":\\\"1\\\",\\\"goodsid\\\":\\\"B530610N\\\",\\\"goodsqty\\\":10,\\\"price\\\":18.9,\\\"subtotal\\\":189.0,\\\"udf1\\\":null,\\\"udf2\\\":null,\\\"udf3\\\":null,\\\"udf4\\\":null,\\\"udf5\\\":null,\\\"udf6\\\":null,\\\"udf7\\\":null,\\\"udf8\\\":null,\\\"udf9\\\":null,\\\"udf10\\\":null}],\\\"udf1\\\":null,\\\"udf2\\\":null,\\\"udf3\\\":null,\\\"udf4\\\":null,\\\"udf5\\\":null,\\\"udf6\\\":null,\\\"udf7\\\":null,\\\"udf8\\\":null,\\\"udf9\\\":null,\\\"udf10\\\":null}\",\"sign\":\"7143447b89842ca3cb4d5859c12d3741b347c66dc3015342d6fc8be343581528\"}";
//        String jsonString = "{\"appId\":\"33dcfbf823b119bd1089eaxxxxxxx\",\"method\":\"m_dispense_callback\",\"timestamp\":\"1698111841683\",\"signType\":\"HMAC_SHA256\",\"content\":{\"ordercode\":\"202307171xxxxxxx\",\"b2bordercode\":\"Q033xxxxxxx\",\"dispense\":[{\"itemcode\":\"2\",\"dispenseno\":\"456123091\",\"goodsid\":\"B401480N\",\"status\":1,\"goodsqty\":100,\"batch\":\"D210225B\",\"validity\":\"2025-12-31\",\"proddate\":\"2021-02-01\",\"udf1\":null,\"udf2\":null,\"udf3\":null,\"udf4\":null,\"udf5\":null,\"udf6\":null,\"udf7\":null,\"udf8\":null,\"udf9\":null,\"udf10\":null}],\"udf1\":null,\"udf2\":null,\"udf3\":null,\"udf4\":null,\"udf5\":null,\"udf6\":null,\"udf7\":null,\"udf8\":null,\"udf9\":null,\"udf10\":null},\"sign\":\"93f070426b6723cecabd88742fe988b3ab028f681e174d217b6c11b1c07cd423\"}";
//        String jsonString = "{\"appId\":\"33dcfbf823b119bd1089ea2exxxxx\",\"method\":\"m_shipments_callback\",\"timestamp\":\"1698112035436\",\"signType\":\"HMAC_SHA256\",\"content\":{\"ordercode\":\"Q033xxxxx\",\"b2bordercode\":\"2023071xxxxx\",\"shipments\":[{\"itemcode\":\"2\",\"dispenseno\":\"456123091\",\"goodsid\":\"B401480N\",\"shipmentsQty\":5,\"batch\":\"D210225B\",\"validity\":\"2025-12-31\",\"proddate\":\"2021-02-01\",\"shipmentsPrice\":26.60000000,\"shipmentsTotalPrice\":2660.00000000,\"shipmentsDate\":\"2023-07-01 13:34:16\",\"targetDate\":\"2021-02-10 13:00:11\",\"signforno\":\"99831871\",\"udf1\":null,\"udf2\":null,\"udf3\":null,\"udf4\":null,\"udf5\":null,\"udf6\":null,\"udf7\":null,\"udf8\":null,\"udf9\":null,\"udf10\":null}],\"udf1\":null,\"udf2\":null,\"udf3\":null,\"udf4\":null,\"udf5\":null,\"udf6\":null,\"udf7\":null,\"udf8\":null,\"udf9\":null,\"udf10\":null},\"sign\":\"d868102b2c8422728d6edb6eb3cc4c0c715ebf7a7250a0c7b0ea6899b669918d\"}";

        String compname = "";
        TLxCallbackLog tLxCallbackLog = new TLxCallbackLog();
        String jsonString = JSONObject.toJSONString(object);
        logger.info("回调："+jsonString);
        tLxCallbackLog.setJsondata(jsonString);
        tLxCallbackLog.setCreatedate(new Date());
        tLxCallbackLog.setCompname("");
        tLxCallbackLogMapper.insert(tLxCallbackLog);

//        String jsonString = "{\"appId\":\"aa44872348b12addb4d500956acd6573\",\"method\":\"m_create_order_callback\",\"timestamp\":\"1722837638927\",\"signType\":\"HMAC_SHA256\",\"content\":\"{\\\"ordercode\\\":\\\"2408050001\\\",\\\"b2bordercode\\\":\\\"P07399425\\\",\\\"total\\\":168.62,\\\"status\\\":1,\\\"errorcode\\\":0,\\\"errormsg\\\":null,\\\"items\\\":[{\\\"itemcode\\\":\\\"1\\\",\\\"goodsid\\\":\\\"C060652001N\\\",\\\"goodsqty\\\":2,\\\"price\\\":84.31,\\\"subtotal\\\":168.62,\\\"udf1\\\":null,\\\"udf2\\\":null,\\\"udf3\\\":null,\\\"udf4\\\":null,\\\"udf5\\\":null,\\\"udf6\\\":null,\\\"udf7\\\":null,\\\"udf8\\\":null,\\\"udf9\\\":null,\\\"udf10\\\":null}],\\\"udf1\\\":null,\\\"udf2\\\":null,\\\"udf3\\\":null,\\\"udf4\\\":null,\\\"udf5\\\":null,\\\"udf6\\\":null,\\\"udf7\\\":null,\\\"udf8\\\":null,\\\"udf9\\\":null,\\\"udf10\\\":null}\",\"sign\":\"e96658b4e787fe4022a0536fa5cde761e7018b8b1f29c07308c27ade1ebded18\"}";

        BaseCallBackResponse baseCallBackResponse = JSONObject.parseObject(jsonString, BaseCallBackResponse.class);
        if(baseCallBackResponse.getMethod().equals("m_create_order_callback")){
            OrderCreateResponse orderCreateResponse= JSONObject.parseObject(baseCallBackResponse.getContent(),
                    new TypeReference<OrderCreateResponse>(){});

            QueryWrapper<TCjLxOrderH> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ordercode",orderCreateResponse.getOrdercode());
            List<TCjLxOrderH> tCjLxOrderHList =  tCjLxOrderHMapper.selectList(queryWrapper);
            if(tCjLxOrderHList.size() == 1){
                TCjLxOrderH tCjLxOrderH = tCjLxOrderHList.get(0);
                compname =tCjLxOrderH.getCompname();
                tCjLxOrderH.setStatus1(orderCreateResponse.getStatus());
                tCjLxOrderH.setErrorcode(orderCreateResponse.getErrorcode());
                tCjLxOrderH.setTotal(orderCreateResponse.getTotal());
                tCjLxOrderH.setB2bordercode(orderCreateResponse.getB2bordercode());
                tCjLxOrderH.setErrormsg(orderCreateResponse.getErrormsg()==null?"":orderCreateResponse.getErrormsg());
                tCjLxOrderH.setUpdatedatetime(new Date());
                tCjLxOrderHMapper.update(tCjLxOrderH,queryWrapper);

                if(null!=orderCreateResponse.getItems()) {
                    for (OrderCreateResponseDetail orderCreateResponseDetail : orderCreateResponse.getItems()) {
                        QueryWrapper<TCjLxOrderD> queryWrapperD = new QueryWrapper<>();
                        queryWrapperD.eq("compname", compname)
                                .eq("ordercode", orderCreateResponse.getOrdercode())
                                .eq("itemcode", orderCreateResponseDetail.getItemcode());
                        List<TCjLxOrderD> tCjLxOrderDList = tCjLxOrderDMapper.selectList(queryWrapperD);
                        if (tCjLxOrderDList.size() == 1) {
                            TCjLxOrderD tCjLxOrderD = tCjLxOrderDList.get(0);
                            tCjLxOrderD.setB2bordercode(orderCreateResponse.getB2bordercode());
                            tCjLxOrderD.setPrice(orderCreateResponseDetail.getPrice());
                            tCjLxOrderD.setGoodsqty(orderCreateResponseDetail.getGoodsqty());
                            tCjLxOrderD.setSubtotal(orderCreateResponseDetail.getSubtotal());
                            tCjLxOrderD.setUpdatedatetime(new Date());

                            tCjLxOrderDMapper.update(tCjLxOrderD, queryWrapperD);
                        }

                    }
                }
            }
        }else if(baseCallBackResponse.getMethod().equals("m_dispense_callback")){//配货

            OrderTakeResponse orderTakeResponse= JSONObject.parseObject(baseCallBackResponse.getContent(),
                    new TypeReference<OrderTakeResponse>(){});


            QueryWrapper<TCjLxOrderH> queryWrapperOrderH = new QueryWrapper<>();
            queryWrapperOrderH.eq("ordercode",orderTakeResponse.getOrdercode());
            List<TCjLxOrderH> tCjLxOrderHList =  tCjLxOrderHMapper.selectList(queryWrapperOrderH);

            if(tCjLxOrderHList.size() == 1){
                TCjLxOrderH tCjLxOrderH = tCjLxOrderHList.get(0);
                compname = tCjLxOrderH.getCompname();
            }


            QueryWrapper<TCjLxOrderTakeH> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("compname",compname).eq("ordercode",orderTakeResponse.getOrdercode());
            List<TCjLxOrderTakeH> tCjLxOrderTakeHList =  tCjLxOrderTakeHMapper.selectList(queryWrapper);
            if(tCjLxOrderTakeHList.size() > 0){

            }else{
                TCjLxOrderTakeH tCjLxOrderTakeH = new TCjLxOrderTakeH();
                tCjLxOrderTakeH.setB2bordercode(orderTakeResponse.getB2bordercode());
                tCjLxOrderTakeH.setCompname(compname);
                tCjLxOrderTakeH.setCreatedatetime(new Date());
                tCjLxOrderTakeH.setOrdercode(orderTakeResponse.getOrdercode());
                tCjLxOrderTakeHMapper.insert(tCjLxOrderTakeH);
            }


            for(OrderTakeResponseDetail orderTakeResponseDetail:orderTakeResponse.getDispense()){
                TCjLxOrderTakeD tCjLxOrderTakeD = new TCjLxOrderTakeD();
                tCjLxOrderTakeD.setB2bordercode(orderTakeResponse.getB2bordercode());
                tCjLxOrderTakeD.setOrdercode(orderTakeResponse.getOrdercode());
                tCjLxOrderTakeD.setCompname(compname);
                tCjLxOrderTakeD.setCreatedatetime(new Date());
                tCjLxOrderTakeD.setItemcode(orderTakeResponseDetail.getItemcode());
                tCjLxOrderTakeD.setDispenseno(orderTakeResponseDetail.getDispenseno());
                tCjLxOrderTakeD.setGoodsid(orderTakeResponseDetail.getGoodsid());
                tCjLxOrderTakeD.setDispenseno(orderTakeResponseDetail.getDispenseno());
                tCjLxOrderTakeD.setStatus(orderTakeResponseDetail.getStatus());
                tCjLxOrderTakeD.setGoodsqty(orderTakeResponseDetail.getGoodsqty());
                tCjLxOrderTakeD.setBatchdata(orderTakeResponseDetail.getBatch());
                tCjLxOrderTakeD.setValidity(orderTakeResponseDetail.getValidity());
                tCjLxOrderTakeD.setProddate(orderTakeResponseDetail.getProddate());
                tCjLxOrderTakeDMapper.insert(tCjLxOrderTakeD);
            }
        }else if(baseCallBackResponse.getMethod().equals("m_shipments_callback")){//发货
            OrderSendResponse orderSendResponse= JSONObject.parseObject(baseCallBackResponse.getContent(),
                    new TypeReference<OrderSendResponse>(){});

            QueryWrapper<TCjLxOrderH> queryWrapperOrderH = new QueryWrapper<>();
            queryWrapperOrderH.eq("ordercode",orderSendResponse.getOrdercode());
            List<TCjLxOrderH> tCjLxOrderHList =  tCjLxOrderHMapper.selectList(queryWrapperOrderH);

            if(tCjLxOrderHList.size() == 1){
                TCjLxOrderH tCjLxOrderH = tCjLxOrderHList.get(0);
                compname = tCjLxOrderH.getCompname();
            }

            QueryWrapper<TCjLxOrderSendH> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("compname",compname).eq("ordercode",orderSendResponse.getOrdercode());
            List<TCjLxOrderSendH> tCjLxOrderSendHList = tCjLxOrderSendHMapper.selectList(queryWrapper);
            if(tCjLxOrderSendHList.size() > 0){

            }else{
                TCjLxOrderSendH tCjLxOrderSendH = new TCjLxOrderSendH();
                tCjLxOrderSendH.setB2bordercode(orderSendResponse.getB2bordercode());
                tCjLxOrderSendH.setCompname(compname);
                tCjLxOrderSendH.setCreatedatetime(new Date());
                tCjLxOrderSendH.setOrdercode(orderSendResponse.getOrdercode());
                tCjLxOrderSendHMapper.insert(tCjLxOrderSendH);
            }


            for(OrderSendResponseDetail orderSendResponseDetail:orderSendResponse.getShipments()){
                TCjLxOrderSendD tCjLxOrderSendD = new TCjLxOrderSendD();
                tCjLxOrderSendD.setB2bordercode(orderSendResponse.getB2bordercode());
                tCjLxOrderSendD.setOrdercode(orderSendResponse.getOrdercode());
                tCjLxOrderSendD.setCompname(compname);
                tCjLxOrderSendD.setCreatedatetime(new Date());
                tCjLxOrderSendD.setItemcode(orderSendResponseDetail.getItemcode());
                tCjLxOrderSendD.setGoodsid(orderSendResponseDetail.getGoodsid());
                tCjLxOrderSendD.setDispenseno(orderSendResponseDetail.getDispenseno());
                tCjLxOrderSendD.setShipmentsqty(orderSendResponseDetail.getShipmentsQty());
                tCjLxOrderSendD.setBatchdata(orderSendResponseDetail.getBatch());
                tCjLxOrderSendD.setValidity(orderSendResponseDetail.getValidity());
                tCjLxOrderSendD.setProddate(orderSendResponseDetail.getProddate());
                tCjLxOrderSendD.setShipmentsprice(orderSendResponseDetail.getShipmentsPrice());
                tCjLxOrderSendD.setShipmentstotalprice(orderSendResponseDetail.getShipmentsTotalPrice());
                tCjLxOrderSendD.setShipmentsdate(orderSendResponseDetail.getShipmentsDate());
                tCjLxOrderSendD.setTargetdate(orderSendResponseDetail.getTargetDate());
                tCjLxOrderSendD.setSignforno(orderSendResponseDetail.getSignforno());

                tCjLxOrderSendDMapper.insert(tCjLxOrderSendD);
            }
        }
    }


    //查询价格
    @Override
    public String queryPrice(String appid,String appsecret,String supplierid,String url,String compname,String ... goodsids) throws Exception {
        //String[] goodsids = {"H022911N","B404811N"};
        QueryPriceDTO queryPriceDTO = createQueryPriceDTO(supplierid,goodsids);
        String content = JSONObject.toJSONString(queryPriceDTO);
        BaseDTO baseDTO = BaseDTO.createBaseDTO(appid,appsecret,content, DzApplicationCommon.M_SEARCH_PRICE);
        logger.info("查询价格请求：" + JSONObject.toJSONString(baseDTO));
        String respJson = HttpPostRequestUtil.sendPostRequest(url, JSONObject.toJSONString(baseDTO));
        logger.info("查询价格响应信息：" + respJson);
        TCjLxLog tCjLxLog = new TCjLxLog();
        tCjLxLog.setCompname(compname);
        tCjLxLog.setCreatedatetime(new Date());
        String respJson1 = "";
        if(respJson.length()>=2000){
             respJson1 = respJson.substring(0,2000);
        }else{
             respJson1 = respJson;
        }

        tCjLxLog.setJsonData(respJson1);
        tCjLxLog.setRemark("拉取价格");
        tCjLxLogMapper.insert(tCjLxLog);

        BaseResponse baseResponse = JSONObject.parseObject(respJson, BaseResponse.class);
        if (200 == baseResponse.getCode()) {
            List<QueryPriceResponse> queryPriceResponses = JSONObject.parseObject(baseResponse.getData(),
                    new TypeReference<List<QueryPriceResponse>>(){});
            for(QueryPriceResponse queryPriceResponse:queryPriceResponses){
                TCjLxWarePrice tCjLxWarePrice = new TCjLxWarePrice();
                tCjLxWarePrice.setCompname(compname);
                tCjLxWarePrice.setCreatedatetime(new Date());
                logger.info("商品编码:"+queryPriceResponse.getGoodsid());
                tCjLxWarePrice.setGoodsid(queryPriceResponse.getGoodsid());
                tCjLxWarePrice.setPrice(queryPriceResponse.getPrice());
                tCjLxWarePriceMapper.insert(tCjLxWarePrice);
            }

        }
        return respJson;
    }

    @Override
    public void queryPriceBatch(String appid,String appsecret,String supplierid,String url,String compname) throws Exception {
        QueryWrapper<TCjLxWarePrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("compname",compname);

        tCjLxWarePriceMapper.delete(queryWrapper);

        List<String> tCjLxWareList = tCjLxWareMapper.selectAll(compname);
        int j = 0;
        String[] stringArray = new String[100];
        for(int i = 0; i<tCjLxWareList.size() ;i++){

            if(j==100){
                j = 0;
                queryPrice(appid,appsecret,supplierid,url,compname,stringArray);
                Arrays.fill(stringArray, null);
                stringArray[j] = tCjLxWareList.get(i);
            }else{
                stringArray[j] = tCjLxWareList.get(i);
            }
            j = j+1;
        }

        if((tCjLxWareList.size() % 100)!=0){
            int actualSize = 0;
            for (int i = 0; i < stringArray.length; i++) {
                if (stringArray[i] != null) {
                    actualSize++;
                } else {
                    break; // 如果遇到 null，说明后面都是空的，可以停止计数
                }
            }
            String[] newArray = Arrays.copyOf(stringArray, actualSize);
            queryPrice(appid,appsecret,supplierid,url,compname,newArray);
        }
    }

    public QueryPriceDTO createQueryPriceDTO(String supplierid,String ... goodsids) {
        QueryPriceDTO queryPriceDTO = new QueryPriceDTO();

        /**
         * 由B2B提供
         */
        queryPriceDTO.setSupplierid(supplierid);

        /**
         * 商品编码集合
         */
        queryPriceDTO.setGoodsid(Arrays.asList(goodsids));

        return queryPriceDTO;
    }

    //查询库存
    @Override
    public String queryStock(String appid,String appsecret,String supplierid,String url,String compname,String ... goodsids) throws Exception {
        QueryStockDTO queryStockDTO = createQueryStockDTO(supplierid,goodsids);
        String content = JSONObject.toJSONString(queryStockDTO);
        BaseDTO baseDTO = BaseDTO.createBaseDTO(appid,appsecret,content, DzApplicationCommon.M_SEARCH_STOCK);
        logger.info("查询库存请求：" + JSONObject.toJSONString(baseDTO));
        String respJson = HttpPostRequestUtil.sendPostRequest(url, JSONObject.toJSONString(baseDTO));
        logger.info("查询库存响应信息：" + respJson);
        TCjLxLog tCjLxLog = new TCjLxLog();
        tCjLxLog.setCompname(compname);
        tCjLxLog.setCreatedatetime(new Date());

        String respJson1 = "";
        if(respJson.length()>=2000){
            respJson1 = respJson.substring(0,2000);
        }else{
            respJson1 = respJson;
        }


        tCjLxLog.setJsonData(respJson1);
        tCjLxLog.setRemark("拉取库存");
        tCjLxLogMapper.insert(tCjLxLog);


        BaseResponse baseResponse = JSONObject.parseObject(respJson, BaseResponse.class);
        if (200 == baseResponse.getCode()) {
            List<QueryStockResponse> queryStockResponses = JSONObject.parseObject(baseResponse.getData(),
                    new TypeReference<List<QueryStockResponse>>(){});
            for(QueryStockResponse queryStockResponse:queryStockResponses){
                TCjLxWareQty tCjLxWareQty = new TCjLxWareQty();
                tCjLxWareQty.setCompname(compname);
                tCjLxWareQty.setCreatedatetime(new Date());
                logger.info("商品编码:"+queryStockResponse.getGoodsid());
                tCjLxWareQty.setGoodsid(queryStockResponse.getGoodsid());
                tCjLxWareQty.setQty(queryStockResponse.getStock().toString());
                tCjLxWareQtyMapper.insert(tCjLxWareQty);
            }
        }
        return respJson;
    }

    @Override
    public void queryStockBatch(String appid,String appsecret,String supplierid,String url,String compname) throws Exception {
        QueryWrapper<TCjLxWareQty> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("compname",compname);

        tCjLxWareQtyMapper.delete(queryWrapper);

        List<String> tCjLxWareList = tCjLxWareMapper.selectAll(compname);
        int j = 0;
        String[] stringArray = new String[100];
        for(int i = 0; i<tCjLxWareList.size() ;i++){

            if(j==100){
                j = 0;
                queryStock(appid,appsecret,supplierid,url,compname,stringArray);
                Arrays.fill(stringArray, null);
                stringArray[j] = tCjLxWareList.get(i);
            }else{
                stringArray[j] = tCjLxWareList.get(i);
            }
            j = j+1;
        }

        if((tCjLxWareList.size() % 100)!=0){
            int actualSize = 0;
            for (int i = 0; i < stringArray.length; i++) {
                if (stringArray[i] != null) {
                    actualSize++;
                } else {
                    break; // 如果遇到 null，说明后面都是空的，可以停止计数
                }
            }
            String[] newArray = Arrays.copyOf(stringArray, actualSize);
            queryStock(appid,appsecret,supplierid,url,compname,newArray);
        }
    }


    public QueryStockDTO createQueryStockDTO(String supplierid,String ... goodsids) {
        QueryStockDTO queryStockDTO = new QueryStockDTO();

        /**
         * 由B2B提供
         */
        queryStockDTO.setSupplierid(supplierid);

        /**
         * 商品编码集合
         */
        queryStockDTO.setGoodsid(Arrays.asList(goodsids));

        return queryStockDTO;
    }


    @Override
    public String createOrder(String addressid,String supplierid,String appid,String appsecret,String url,String compname,CreateOrderParam createOrderParam) throws Exception {
        PlaceAnOrderDTO placeAnOrderDTO = createPlaceAnOrderDTO(addressid,supplierid,createOrderParam);
        String content = JSONObject.toJSONString(placeAnOrderDTO);
        BaseDTO baseDTO = BaseDTO.createBaseDTO(appid,appsecret,content, DzApplicationCommon.M_CREATE_ORDER);
        String respJson = HttpPostRequestUtil.sendPostRequest(url, JSONObject.toJSONString(baseDTO));
        logger.info("响应信息：" + respJson);
        BaseResponse baseResponse = JSONObject.parseObject(respJson, BaseResponse.class);
        if (200 == baseResponse.getCode()) {
            PlaceAnOrderResponse placeAnOrderResponse = JSONObject.parseObject(baseResponse.getData(), PlaceAnOrderResponse.class);
            TCjLxOrderH tCjLxOrderH = new TCjLxOrderH();
            tCjLxOrderH.setOrdercode(placeAnOrderDTO.getOrdercode());
            tCjLxOrderH.setCompname(compname);
            tCjLxOrderH.setCreatedatetime(new Date());
            tCjLxOrderH.setPaymethod(createOrderParam.getPaymethod());
            tCjLxOrderH.setRemark(createOrderParam.getRemark());
            tCjLxOrderHMapper.insert(tCjLxOrderH);

            for(PlaceAnOrderEntryDTO placeAnOrderEntryDTO:placeAnOrderDTO.getItems()){
                TCjLxOrderD tCjLxOrderD = new TCjLxOrderD();
                tCjLxOrderD.setOrdercode(placeAnOrderDTO.getOrdercode());
                tCjLxOrderD.setCompname(compname);
                tCjLxOrderD.setItemcode(Integer.valueOf(placeAnOrderEntryDTO.getItemcode()));
                tCjLxOrderD.setGoodsid(placeAnOrderEntryDTO.getGoodsid());
                tCjLxOrderD.setGoodsorderqty(placeAnOrderEntryDTO.getGoodsqty());
                tCjLxOrderD.setOrderprice(placeAnOrderEntryDTO.getExceptprice());
                tCjLxOrderD.setCreatedatetime(new Date());
                tCjLxOrderDMapper.insert(tCjLxOrderD);
            }

            logger.info(JSONObject.toJSONString(placeAnOrderResponse));
        }
        return respJson;
    }

    @Override
    public String createOrderJm(String addressid,String supplierid,String appid,String appsecret,String url,String compname,String ordercode) throws Exception {
        QueryWrapper<TCjLxOrderH> queryWrapperH = new QueryWrapper<>();
        queryWrapperH.eq("compname",compname).eq("ordercode",ordercode);
        List<TCjLxOrderH> tCjLxOrderHList =  tCjLxOrderHMapper.selectList(queryWrapperH);
        if(tCjLxOrderHList.size()>0){
            TCjLxOrderH tCjLxOrderH = tCjLxOrderHList.get(0);
            CreateOrderParam createOrderParam = new CreateOrderParam();
            createOrderParam.setPaymethod(tCjLxOrderH.getPaymethod());
            createOrderParam.setRemark(tCjLxOrderH.getRemark());
            createOrderParam.setOrderCode(tCjLxOrderH.getOrdercode());

            List<CreateOrderParamDetail> createOrderParamDetailList =
                    new ArrayList<>();

            QueryWrapper<TCjLxOrderD> queryWrapperD = new QueryWrapper<>();
            queryWrapperD.eq("compname",compname).eq("ordercode",ordercode);
            List<TCjLxOrderD> tCjLxOrderDList =  tCjLxOrderDMapper.selectList(queryWrapperD);

            for(TCjLxOrderD tCjLxOrderD:tCjLxOrderDList){
                CreateOrderParamDetail createOrderParamDetail = new CreateOrderParamDetail();
                createOrderParamDetail.setQty(tCjLxOrderD.getGoodsorderqty());
                createOrderParamDetail.setPrice(tCjLxOrderD.getOrderprice());
                createOrderParamDetail.setGoodsid(tCjLxOrderD.getGoodsid());
                createOrderParamDetail.setItemcode(tCjLxOrderD.getItemcode().toString());
                createOrderParamDetailList.add(createOrderParamDetail);
            }
            createOrderParam.setCreateOrderParamDetailList(createOrderParamDetailList);




            PlaceAnOrderDTO placeAnOrderDTO = createPlaceAnOrderJmDTO(addressid,supplierid,createOrderParam);
            String content = JSONObject.toJSONString(placeAnOrderDTO, SerializerFeature.WriteMapNullValue);
            BaseDTO baseDTO = BaseDTO.createBaseDTO( appid, appsecret,content, DzApplicationCommon.M_CREATE_ORDER);
            logger.info("创建订单发送数据"+JSONObject.toJSONString(baseDTO, SerializerFeature.WriteMapNullValue));
            String respJson = HttpPostRequestUtil.sendPostRequest(url, JSONObject.toJSONString(baseDTO, SerializerFeature.WriteMapNullValue));
            logger.info("创建订单响应信息：" + respJson);
            BaseResponse baseResponse = JSONObject.parseObject(respJson, BaseResponse.class);
            if (200 == baseResponse.getCode()) {
                tCjLxOrderH.setStatus1(0);
                QueryWrapper<TCjLxOrderH> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("compname",compname).eq("ordercode",tCjLxOrderH.getOrdercode());
                tCjLxOrderHMapper.update(tCjLxOrderH,queryWrapper);
            }

        }
        return "SUCCESS";
    }

    public PlaceAnOrderDTO createPlaceAnOrderDTO(String addressid,String supplierid,CreateOrderParam createOrderParam) {
        PlaceAnOrderDTO placeAnOrderDTO = new PlaceAnOrderDTO();
        /**
         * 由B2B提供
         */
        placeAnOrderDTO.setAddressid(addressid);

        /**
         * 由B2B提供
         */
        placeAnOrderDTO.setSupplierid(supplierid);

        /**
         * 接入方自定义订单编码，需要替换成接入方实际的订单编号
         */
        String orderCode = String.valueOf(System.currentTimeMillis());

        placeAnOrderDTO.setOrdercode(orderCode);

        logger.info("订单编号"+orderCode);

        /**
         * 运费
         */
        placeAnOrderDTO.setFreight(new BigDecimal("0"));

        /**
         * 支付方式，按需填写
         */
        placeAnOrderDTO.setPaymethod(createOrderParam.getPaymethod());

        /**
         * 备注
         */
        placeAnOrderDTO.setRemark(createOrderParam.getRemark());

        //构建下单细项
        int itemcode = 0;
        List<PlaceAnOrderEntryDTO> items = new ArrayList<PlaceAnOrderEntryDTO>(createOrderParam.getCreateOrderParamDetailList().size());
        for (CreateOrderParamDetail createOrderParamDetail : createOrderParam.getCreateOrderParamDetailList()) {
            PlaceAnOrderEntryDTO placeAnOrderEntryDTO = new PlaceAnOrderEntryDTO();
            /**
             * 订单项编码，区分不同订单项，同一订单细项不可重复，可用1、2、3……简单区分
             */
            placeAnOrderEntryDTO.setItemcode(String.valueOf(itemcode++));

            /**
             * 商品编码
             */
            placeAnOrderEntryDTO.setGoodsid(createOrderParamDetail.getGoodsid());

            /**
             * 下单数量
             */
            placeAnOrderEntryDTO.setGoodsqty(createOrderParamDetail.getQty());

            /**
             * 期望价格,传商品的期望价格
             */
            placeAnOrderEntryDTO.setExceptprice(createOrderParamDetail.getPrice());

            items.add(placeAnOrderEntryDTO);
        }
        placeAnOrderDTO.setItems(items);
        return placeAnOrderDTO;
    }


    public PlaceAnOrderDTO createPlaceAnOrderJmDTO(String addressid,String supplierid,CreateOrderParam createOrderParam) {
        PlaceAnOrderDTO placeAnOrderDTO = new PlaceAnOrderDTO();
        /**
         * 由B2B提供
         */
        placeAnOrderDTO.setAddressid(addressid);

        /**
         * 由B2B提供
         */
        placeAnOrderDTO.setSupplierid(supplierid);

        /**
         * 接入方自定义订单编码，需要替换成接入方实际的订单编号
         */
        //String orderCode = String.valueOf(System.currentTimeMillis());

        placeAnOrderDTO.setOrdercode(createOrderParam.getOrderCode());

        logger.info("订单编号"+createOrderParam.getOrderCode());

        /**
         * 运费
         */
        placeAnOrderDTO.setFreight(new BigDecimal("0"));

        /**
         * 支付方式，按需填写
         */
        placeAnOrderDTO.setPaymethod(createOrderParam.getPaymethod());

        /**
         * 备注
         */
        placeAnOrderDTO.setRemark(createOrderParam.getRemark());

        //构建下单细项
        int itemcode = 0;
        List<PlaceAnOrderEntryDTO> items = new ArrayList<PlaceAnOrderEntryDTO>(createOrderParam.getCreateOrderParamDetailList().size());
        for (CreateOrderParamDetail createOrderParamDetail : createOrderParam.getCreateOrderParamDetailList()) {
            PlaceAnOrderEntryDTO placeAnOrderEntryDTO = new PlaceAnOrderEntryDTO();
            /**
             * 订单项编码，区分不同订单项，同一订单细项不可重复，可用1、2、3……简单区分
             */
            placeAnOrderEntryDTO.setItemcode(createOrderParamDetail.getItemcode());

            /**
             * 商品编码
             */
            placeAnOrderEntryDTO.setGoodsid(createOrderParamDetail.getGoodsid());

            /**
             * 下单数量
             */
            placeAnOrderEntryDTO.setGoodsqty(createOrderParamDetail.getQty());

            /**
             * 期望价格,传商品的期望价格
             */
            placeAnOrderEntryDTO.setExceptprice(createOrderParamDetail.getPrice());

            items.add(placeAnOrderEntryDTO);
        }
        placeAnOrderDTO.setItems(items);
        return placeAnOrderDTO;
    }

    @Override
    public String queryOrderStatus(String appid,String appsecret,String url,String compname,String orderCode) throws Exception {
        QueryOrderStatusDTO queryOrderStatusDTO = createQueryOrderStatusDTO(orderCode);
        String content = JSONObject.toJSONString(queryOrderStatusDTO);
        BaseDTO baseDTO = BaseDTO.createBaseDTO(appid,appsecret,content, DzApplicationCommon.M_SEARCH_ORDER);
        String respJson = HttpPostRequestUtil.sendPostRequest(url, JSONObject.toJSONString(baseDTO));
        logger.info("响应信息：" + respJson);
        BaseResponse baseResponse = JSONObject.parseObject(respJson, BaseResponse.class);
        if (200 == baseResponse.getCode()) {
            QueryOrderStatusResponse queryOrderStatusResponse = JSONObject.parseObject(baseResponse.getData(), QueryOrderStatusResponse.class);
            logger.info(JSONObject.toJSONString(queryOrderStatusResponse));
        }
        return respJson;
    }


    public QueryOrderStatusDTO createQueryOrderStatusDTO(String ordercode) {
        QueryOrderStatusDTO queryOrderStatusDTO = new QueryOrderStatusDTO();
        /**
         * B2B或接入方订单编号
         */
        queryOrderStatusDTO.setB2bordercode(ordercode);
        return queryOrderStatusDTO;
    }


    public static void main(String[] args) throws JsonProcessingException {
        // 假设有一个包含多个ASN数据的源，例如数据库查询结果或其他来源
//        List<ASN> asnList = new ArrayList<>();
//
//        // 用数据源填充ASN对象
//        for (int i = 0; i < 10; i++) {
//            ASN asn = new ASN("A20200414", "2020-03-12", 1634869, "113001" + i, "盒", 20, i, "lot" + i, "2020-01-01", "2020-12-31");
//            asnList.add(asn);
//        }
//
//        // 创建ASNList对象
//        ASNList asnListObj = new ASNList(asnList);
//
//        // 此处可以将asnListObj转换为JSON，或者进行其他操作
//        ObjectMapper objectMapper = new ObjectMapper();
//        String json = objectMapper.writeValueAsString(asnList);
//
//        System.out.println(json);
    }

    @Override
    public String uploadMom() throws JsonProcessingException {
        List<Map<String,Object>> tCjLxOrderDUploadMomList  = tCjLxOrderDMapper.selectTCjLxOrderDUploadMom();

        List<ASN> asnList = new ArrayList<>();

        // 用数据源填充ASN对象
        for (Map<String,Object> map:tCjLxOrderDUploadMomList) {
            ASN asn = new ASN();
            asn.setAsnNo(map.get("ASNNO").toString());
            asn.setAsnDate(map.get("ASNDATE").toString());
            asn.setOrderNo(Integer.parseInt(map.get("ORDERNO").toString()));
            asn.setItem(map.get("ITEM").toString());
            asn.setUnit(map.get("UNIT").toString());
            //asn.setQty(map.get("asnNo").toString());
            asn.setAsnQty(new BigDecimal(map.get("ASNQTY").toString()));
            asn.setLot(map.get("LOT").toString());
            asn.setProdDate(map.get("PRODDATE").toString());
            asn.setValidDate(map.get("VALIDDATE").toString());
            asnList.add(asn);
        }

        // 创建ASNList对象
//        ASNList asnListObj = new ASNList(asnList);

        // 此处可以将asnListObj转换为JSON，或者进行其他操作
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(asnList);

        System.out.println(json);
        return null;
    }
}
